# -*- coding: utf-8 -*-
import datetime
import os

from models.punch import Punch
from models.user import User

N = 0


def file_name(file_dir):
    for root, dirs, files in os.walk(file_dir):
        return [root + '/' + file for file in files if ".xlsx" in file]


import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.ticker as ticker
import numpy as np

plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号


def file_plot(index, values, label):
    print(values)
    def x_fmt_func(x, pos=None):
        idx = np.clip(int(x + 0.5), 0, len(index) - 1)
        return index[idx]
    fig = plt.figure(figsize=(24, 8), dpi=80)
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(index, values, label=label, color='r', linewidth=1, linestyle="-" )
    # try:
    #     ax.xaxis.set_major_formatter(ticker.FuncFormatter(x_fmt_func))
    #     ax.grid(True)
    #     plt.show()
    # except Exception as e:
    #     pass
    plt.savefig("./images/{}.png".format(label))


import pandas as pd


def file_load(file):
    user = User()
    punch = Punch()
    file_name = str(file).split('.xlsx')[0]
    file_name = str(file_name).split('/')[-1]
    try:
        os.mkdir("./images/{}".format(file_name))
    except Exception as e:
        pass
    d = pd.read_excel(file, names=[str(i) for i in range(47)])
    data = pd.DataFrame(d)
    data = data.rename(columns={'7': 'Start', '9': 'End', '0': 'Name', '5': 'Date'})
    data = data.loc[3:]
    data_end = data[['End', 'Name', 'Date']]
    data_end = data_end.dropna(axis=0, how='any')
    data_group = data_end.reset_index().groupby(["Name"])
    names = data_group.groups.keys()
    have_foreach = []
    for name in names:
        user.user_create(name=name)
        user_data = user.user_info_name(name=name)
        for i in range(len(data)):
            if i in have_foreach:
                continue
            if str(data.iloc[i]['Name']) == name:
                if "星期六" in str(data.iloc[i]['Date']) or "星期日" in str(data.iloc[i]['Date']):
                    continue
                record_time = "20" + str(data.iloc[i]['Date']).split(" ")[0]
                if "次日" in str(data.iloc[i]['Time']):
                    punch_time = record_time + " "+str(data.iloc[i]['Time']).split(" ")[1]
                    punch_time = datetime.datetime.strptime(punch_time, '%Y-%m-%d %H:%M')
                    delta = datetime.timedelta(days=1)
                    n_days = punch_time + delta
                    punch_time = n_days.strftime('%Y-%m-%d %H:%M')
                else:
                    punch_time = record_time + " " + data.iloc[i]['Time']
                punch.punch_create(punch_time=punch_time,record_time=record_time+" 19:30",user=user_data.get("id"))

def save_ecel():
    pass


if __name__ == '__main__':
    files = file_name("./files")
    for file in files:
        data = file_load(file)
        # print(data)
    # print(files)
